<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Service\CommonService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class RushCouponController extends Controller
{

    public $redis;

    public function __construct()
    {
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1', 6379);
    }

    /**
     * 优惠券抢购库存预热
     * @param $activity_id
     * @param $activity_stock
     * @param $activity_exit_time
     * @param $activity_start_time
     * User : 邢洋洋
     * Data : 2022/11/17
     * Time : 20:18
     */
    public function rushBuy($activity_id, $activity_stock, $activity_exit_time, $activity_start_time)
    {
        if ($activity_id != null) {
            for ($i = 0; $i < $activity_stock; $i++) {
                //库存进入redis队列 进行库存的预热
                Redis::lpush('rushBuy_number' . $activity_id, 1);
            }
            $this->redis->set('rushBuy_time' . $activity_id, json_encode(['start_time' => strtotime($activity_start_time), 'end_time' => strtotime($activity_exit_time)]), strtotime($activity_exit_time) - time());
        }
    }

    public function storeCombination($activity_id, $activity_stock)
    {
        if ($activity_id != null) {
            for ($i = 0; $i < $activity_stock; $i++) {
                //库存进入redis队列 进行库存的预热
                Redis::lpush('store_combination' . $activity_id, 1);
            }
        }
    }
    /**
     * 优惠券抢购
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function rushBuyCoupon(Request $request)
    {
        $userId = intval($request->input('activity_id'));//uid
        $activityId = intval($request->input('activity_id'));//抢购活动id
        if ($activityId == '') {
            return CommonService::fail(9999,'参数错误','');
        }
        $activity = GrCouponActivity::where('activity_id', $activityId)->first();
        $couponId = $activity->coupon_id;
        $couponSource = 3;//来源 3 代表免费领取
        $number = Redis::llen('rushBuy_number' . $activityId);//查询库存长度
        if (!$number) {
            return ReturnService::failedReturn('库存不足');
        }
        $startTime = $activity->activity_start_time;//开始结束时间
        $endTime = $activity->activity_exit_time;
        if (time() >= strtotime($startTime)) { //判断抢购的是否开始与结束
            if (time() < strtotime($endTime)) {
                $activity = Redis::get('activity' . $activityId . $userId);
                if (!$activity) {//验证是否抢购过
                    //优惠券信息
                    $couponData = [ //优惠券信息
                        'coupon_id' => $couponId,
                        'user_id' => $userId,
                        'coupon_source' => $couponSource,
                        'collection_time' => date('Y-m-d h:i:s')
                    ];
                    $redis = Redis::connection();
                    $key = 'redis_test_key';
                    //获取redis锁实例        参数1：redis连接实例 参数2：锁名称 参数3：超时5秒释放锁
                    $redisLock = new RedisLock($redis, $key . '_lock', 10); //如锁10秒后未释放就自动释放
                    $res = $redis->get($key);
                    if (empty($res)) {
                        //获取生成锁
                        if ($redisLock->acquire()) {
                            //执行库存扣减和优惠券生成 事件分发
                            $coupon = CouponMonitor::dispatch($couponData, $activityId);
                            if ($coupon) {  //设置优惠券过的抢购标识
                                Redis::setex('activity' . $activityId . $userId, strtotime($endTime) - time(), 1);//抢购标识
                                sleep(10);
                                $redisLock->release(); //释放锁
                                return ReturnService::successReturn('抢购成功');
                            }
                            $redisLock->release(); //释放锁
                            return ReturnService::failedReturn('抢购失败');
                        }
                    }
                    return ReturnService::failedReturn('手速慢了');
                }
                return ReturnService::failedReturn('请勿重复抢购');
            }
            return ReturnService::failedReturn('抢购已结束');
        }
        return ReturnService::failedReturn('抢购未开始');
    }


}
